<?php

namespace App\Controller\Admin;

use App\Agent\ChatAgent;
use App\Agent\RedisQueueAgent;
use App\Constants\ErrorCode;
use App\Constants\RedisKey;
use App\Controller\InsideService\GameConfigInside;
use App\Controller\InsideService\GameUserInside;
use App\Controller\InsideService\PaySenderInside;
use App\Controller\InsideService\ToolsInside;
use App\Middleware\AdminMiddleware;
use App\Model\QmGameOrder;
use App\Model\QmGameVersion;
use Exception;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

#[Controller(prefix: '/admin/Tools'), Middleware(AdminMiddleware::class)]
class ToolsController extends BaseController {

    #[PostMapping(path: 'userAvatar')]
    public function userAvatar(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->userAvatar(
            $game_hash, $openid
        );
    }

    #[PostMapping(path: 'roleSkill')]
    public function roleSkill(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');
        $hero_id = $this->request->post('hero_id', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->roleSkill(
            $game_hash, $openid, $hero_id
        );
    }

    #[PostMapping(path: 'closeServer')]
    public function closeServer(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $time = $this->request->post('start_time', '');
        $endTime = $this->request->post('end_time', '');
        $content = $this->request->post('content', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->closeServer(
            $game_hash, $time, $endTime, $content
        );
    }

    #[PostMapping(path: 'roleLastDungeon')]
    public function roleLastDungeon(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');
        $hero_id = $this->request->post('hero_id', '');
        $json = $this->request->post('last_dungeon', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->roleLastDungeon([
            'game_hash'    => $game_hash,
            'openid'       => $openid,
            'hero_id'      => $hero_id,
            'last_dungeon' => $json,
        ]);
    }

    #[PostMapping(path: 'getRoleUnique')]
    public function getRoleUnique(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');
        $hero_id = $this->request->post('hero_id', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->getRoleUnique(
            $game_hash, $openid, $hero_id
        );
    }

    /**
     * 描述: 清除角色战令领取记录
     * 日期: 2023/4/27 14:42
     * @return array
     * @throws Exception
     * @author: cinder
     */
    #[PostMapping(path: 'clearRoleWarOrder')]
    public function clearRoleWarOrder(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');
        $hero_id = $this->request->post('hero_id', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->clearRoleWarOrder(
            $game_hash, $openid, $hero_id
        );
    }

    #[PostMapping(path: 'createEquipment')]
    public function createEquipment(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');
        $hero_id = $this->request->post('hero_id', '');
        $item_id = $this->request->post('item_id', '');
        $extra_effect_id = $this->request->post('extra_effect_id', '');
        $is_abyss = $this->request->post('is_abyss', false);
        $abyss_effect_id = $this->request->post('abyss_effect_id', '');

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->createEquipment(
            $game_hash, $openid, $hero_id, $item_id, $extra_effect_id, $is_abyss, $abyss_effect_id
        );
    }

    #[PostMapping(path: 'backOrder')]
    public function backOrder(): array {
        $orderNum = $this->request->post('order_num', '');

        $orderInfo = QmGameOrder::query()->where('order_num', $orderNum)->first();
        if ($orderInfo) {
            try {
                var_dump($orderInfo->toArray());
                (new PaySenderInside())->sendReward($orderInfo->toArray());
                $orderInfo->status = 3;//金手指补单状态
                $orderInfo->save();

                return $this->buildSuccess();
            } catch (Exception $e) {
                var_dump($e->getMessage());
                return $this->buildFailed(ErrorCode::NOT_EXISTS, '订单版本不正确');
            }
        } else {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '订单不存在');
        }
    }


    /**
     * 描述: 线下充值
     * 日期: 2023/3/16 09:55
     * @return array
     * @throws Exception
     * @author: cinder
     */
    #[PostMapping(path: 'offlineTopUp')]
    public function offlineTopUp(): array {
        //获取参数
        $data['game_hash'] = $this->request->post('game_hash', '');
        $data['version'] = $this->request->post('version', '');
        $data['openid'] = $this->request->post('openid', '');
        $data['platform'] = $this->request->post('platform', '');
        $data['hero_id'] = $this->request->post('hero_id', '');
        $data['gear'] = $this->request->post('gear', '');

        //必须存在档位参数
        if (empty($data['gear'])) {
            return $this->buildFailed(ErrorCode::EMPTY_PARAMS, '缺少档位参数');
        }

        //获取版本信息 如果是停服状态 无法下一步
        $versionInfo = QmGameVersion::query()->where([
            ['game_hash', '=', $data['game_hash']],
            ['version', '=', $data['version']]
        ])->first();

        if (empty($versionInfo) || $versionInfo['status'] === 4) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '游戏版本不存在或者已经停服');
        }

        //判断是否存在角色
        $role_info = (new GameUserInside())->setCode($versionInfo['connection_code'])->getExistRole($data);

        //如果存在角色 就创建一个未支付的订单 去请求发送点券接口 成功执行 修改订单状态为4 线下订单
        if ($role_info) {
            //获取配置信息
            $shopConf = (new GameConfigInside())->setCode($versionInfo['connection_code'])->getConfInfoByKey(
                'shop_info', $data['game_hash'], 'id'
            );

            //获取配置 金额
            $money = (int)substr($shopConf[$data['gear']]['buy_value'], 1, -1);

            //生成订单号
            $orderNum = date('YmdHis') . md5(uniqid('', true) . $data['game_hash'] . 'QM_ONLINE');

            try {
                $model = new QmGameOrder();
                $model->game_hash = $data['game_hash'];
                $model->openid = $data['openid'];
                $model->uid = $role_info['uid'];
                $model->role_id = $role_info['role_id'];
                $model->hero_id = $data['hero_id'];
                $model->order_num = $orderNum;
                $model->platform = $data['platform'];
                $model->goods_id = $data['gear'];
                $model->prepay_id = '';
                $model->money = $money;
                $model->number = 1;
                $model->status = 0;
                $model->check = 0;
                $model->version = $versionInfo['version'];
                $model->create_date = date('Y-m-d');
                $model->save();
                //发放点券 成功执行 修改订单状态为4 线下订单
                (new PaySenderInside())->sendReward([
                    'game_hash' => $data['game_hash'],
                    'version'   => $versionInfo['version'],
                    'goods_id'  => $data['gear'],
                    'uid'       => $role_info['uid'],
                    'role_id'   => $role_info['role_id'],
                    'platform'  => $data['platform'],
                    'order_num' => $orderNum,
                    'openid'    => $data['openid'],
                    'money'     => $money,
                ]);
                QmGameOrder::query()->where('order_num', $orderNum)->update(['status' => 4]);
            } catch (Exception $e) {
                return $this->buildFailed(ErrorCode::NOT_EXISTS, '点券发放失败,请联系管理员');
            }

            return $this->buildSuccess();
        }
        return $this->buildFailed(ErrorCode::NOT_EXISTS, '角色不存在');
    }

    /**
     * 全服禁言和解除禁言
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping(path: 'mute')]
    public function mute(): array {
        $game_hash = $this->request->post('game_hash', '');
        $mute = $this->request->post('mute', 0);

        $chatRedis = (ApplicationContext::getContainer())->get(ChatAgent::class);
        $redisKey = RedisKey::GM_CHAT_PRE . ':SystemMute:' . $game_hash;
        $chatRedis->set($redisKey, $mute);
        return $this->buildSuccess();
    }

    /**
     * app强制更新 相关数据内容
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping(path: 'getAppUpdate')]
    public function getAppUpdate(): array {
        $isTest = $this->request->post('is_test', 0);//是否是测试服，可以用来获取测试服最新版本号

        try {
            $redis = (ApplicationContext::getContainer())->get(RedisQueueAgent::class);
            $appRedisKey = RedisKey::GM_PLATFORM . 'AppUpdate:' . $isTest;
            $return['info'] = $redis->exists($appRedisKey) ? $redis->get($appRedisKey) : '';

            return $this->buildSuccess($return);
        } catch (Exception $e) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, $e->getMessage());
        }
    }

    /**
     * 保存app强制更新
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping(path: 'saveAppUpdate')]
    public function saveAppUpdate(): array {
        $isTest = $this->request->post('is_test', 0);//是否是测试服，可以用来获取测试服最新版本号
        $info = $this->request->post('info', '');//json格式 便于前端自己修改和使用

        try {
            $redis = (ApplicationContext::getContainer())->get(RedisQueueAgent::class);
            $appRedisKey = RedisKey::GM_PLATFORM . 'AppUpdate:' . $isTest;
            $redis->set($appRedisKey, $info);

            return $this->buildSuccess();
        } catch (Exception $e) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, $e->getMessage());
        }
    }

    /**
     * 描述: 每日累充返利发送邮件
     * @return array
     * @throws Exception
     */
    #[PostMapping(path: 'dailyRecharge')]
    public function dailyRecharge(): array {
        $userDataArr = $this->uInfo();
        $game_hash = $this->request->post('game_hash', '');
        $openid = $this->request->post('openid', '');
        $hero_id = $this->request->post('hero_id', '');
        $gear = $this->request->post('gear', '');
        $date = $this->request->post('checkDate', '');
        if (empty($date)) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '请传入日期');
        }
        $date = strtotime($date);
        if ($date >= time()) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '返利日期不能大于今天');
        }

        return (new ToolsInside())->setCode($userDataArr['connection_code'])->dailyRecharge(
            $game_hash, $openid, $hero_id, $gear, $date
        );
    }
}